import {
  getAddressList,
  searchUser,
  sendRequest,
  getRequestList,
  requestDetail,
  requestHandle,
  deleteFriend,
  requestCount,
  userDetail
} from '@/api/contact'
import tools from '@/utils/tools'
import { groupList } from '@/api/group'

const state = {
  // rightHeader所需
  rightHeaderData: {},
  // 通讯录字母空列表
  alphabetList: [],
  // 通讯录列表
  addressList: [],
  // 搜索/点击的好友信息
  userInfo: {},
  // 当前选中的导航id
  current_navId: '',
  // 群组列表
  groupList: [],
  // 好友请求列表
  requestList: [],
  // 未读好友申请数量
  unreadCount: 0,
  // 最近申请同意的好友id
  recentAgreeId: null
}
const mutations = {
  // 建立通讯录空列表
  reset_addressList (state) {
    state.alphabetList = []
    for (let i = 0; i < 26; i++) {
      state.alphabetList.push({ code: String.fromCharCode(65 + i), data: [] })
    }
  },
  // 设置rightHeader
  set_rightHeader (state, obj) {
    state.rightHeaderData = obj
  },
  // 设置通讯录列表
  set_addressList (state, list) {
    state.addressList = list
  },
  // 设置搜索的好友信息
  set_userInfo (state, obj) {
    state.userInfo = obj
  },
  // 设置群组列表
  set_groupList (state, list) {
    state.groupList = list
  },
  // 设置好友请求列表
  set_requestList (state, list) {
    state.requestList = list
  },
  // 设置当前导航id
  set_currentId (state, id) {
    state.current_navId = id
  },
  // 设置未读消息数量
  set_unreadCount (state, count) {
    state.unreadCount = count
  },
  // 设置最近同意的好友ID
  set_recentAgreeId (state, id) {
    state.recentAgreeId = id
  }
}

const getters = {
  unreadReal (state) {
    return state.unreadCount
  }
}

const actions = {
  // 获取通讯录列表
  getMyAddressList ({ state, dispatch, commit, rootState }) {
    return new Promise((resolve, reject) => {
      getAddressList().then(async res => {
        if (res.data.code === 200) {
          await commit('reset_addressList')
          if (res.data.data === null) {
            res.data.data = []
          }
          res.data.data.forEach(item => {
            if (!rootState.chatInformation.userList[item.user_id]) {
              commit('chatInformation/add_user', {
                userID: item.user_id,
                userInfo: {
                  user_name: item.user_name,
                  user_img_id: item.user_img,
                  in_contact: true,
                  remarks: item.remarks,
                  user_phone: item.user_phone
                }
              }, { root: true })
            }
          })
          commit('set_addressList', res.data.data)
          // }
          resolve(res)
        }
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 搜索用户
  searchUser ({ commit, dispatch, rootState }, phone) {
    return new Promise((resolve, reject) => {
      searchUser(phone).then(async res => {
        if (res.data && res.data.code === 200) {
          if (res.data.data.exists) {
            if (!rootState.chatInformation.userList[res.data.data.info.user_id]) {
              commit('chatInformation/add_user', {
                userID: res.data.data.info.user_id,
                userInfo: {
                  user_name: res.data.data.info.user_name,
                  user_img_id: res.data.data.info.user_img,
                  in_contact: tools.isFriend(res.data.data.info.user_id),
                  remarks: res.data.data.info.remarks,
                  user_phone: res.data.data.info.user_phone
                }
              }, { root: true })
            }
            commit('set_userInfo', { ...res.data.data.info, in_contact: res.data.data.in_contact })
          }
        }
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 发起好友请求
  sendFriendRequest (context, { invitationTo, invitationMsg }) {
    return new Promise((resolve, reject) => {
      sendRequest(invitationTo, invitationMsg).then(res => {
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 获取群组列表
  getGroupList ({ commit, dispatch, rootState }) {
    return new Promise((resolve, reject) => {
      groupList().then(async res => {
        if (res.data && res.data.code === 200 && res.data.data) {
          for (let i = 0; i < res.data.data.length; i++) {
            const result = await dispatch('groups/getGroupInfo', res.data.data[i].group_id, { root: true })
            if (result.data && result.data.code === 200) {
              if (!rootState.chatInformation.groupList[res.data.data[i].group_id]) {
                commit('chatInformation/add_group', {
                  groupID: res.data.data[i].group_id,
                  groupInfo: { group_name: res.data.data[i].group_name, group_sponsor: result.data.data.group_sponsor, group_img_id: result.data.data.group_img }
                }, { root: true })
              }
            }
          }
          commit('set_groupList', res.data.data)
        } else {
          commit('set_groupList', [])
        }
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 获取好友请求数量
  getRequestCount ({ commit }) {
    return new Promise((resolve, reject) => {
      requestCount().then(res => {
        if (res.data && res.data.code === 200) {
          commit('set_unreadCount', res.data.data)
        }
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 获取好友请求列表
  getFriendsRequestList ({ commit, dispatch, rootState }) {
    return new Promise((resolve, reject) => {
      getRequestList().then(async res => {
        if (res.data && res.data.code === 200) {
          for (let i = 0; i < res.data.data.length; i++) {
            if (!rootState.chatInformation.userList[res.data.data[i].user_id]) {
              const result = await dispatch('getUserDetail', res.data.data[i].user_id)
              if (result.data && result.data.code === 200) {
                commit('chatInformation/add_user', {
                  userID: res.data.data[i].user_id,
                  userInfo: {
                    user_name: res.data.data[i].user_name,
                    user_img_id: res.data.data[i].user_img,
                    in_contact: tools.isFriend(res.data.data[i].user_id),
                    remarks: result.data.data.info.remarks,
                    user_phone: result.data.data.info.user_phone
                  }
                }, { root: true })
              }
            }
          }
          commit('set_requestList', res.data.data)
        }
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 查看好友请求详情
  examineRequestDetail ({ commit }, invitationID) {
    return new Promise((resolve, reject) => {
      requestDetail(invitationID).then(res => {
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 处理好友请求
  handleRequest (context, { invitationID, invitationState }) {
    return new Promise((resolve, reject) => {
      requestHandle(invitationID, invitationState).then(res => {
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 删除好友
  friendDelete ({ commit, rootState }, { deleteID }) {
    return new Promise((resolve, reject) => {
      deleteFriend(deleteID).then(res => {
        if (rootState.chatInformation.chatInformation.some(item => item.user_id === deleteID)) {
          commit('chatInformation/reset_identify', {
            id: deleteID,
            bool: false
          }, { root: true })
          commit('chatInformation/delete_messages', {
            id: deleteID,
            idType: 1
          })
        }
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 获取用戶信息详情
  getUserDetail (context, userID) {
    return new Promise((resolve, reject) => {
      userDetail(userID).then(res => {
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
